package org.kalai.unifypay.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.kalai.unifypay.Constant;
import org.kalai.unifypay.bean.Member;
import org.kalai.unifypay.bean.PartnerBiz;
import org.kalai.unifypay.util.CommonUtil;
import org.kalai.unifypay.util.DBUtil;
import org.kalai.unifypay.util.DataDao;
import org.kalai.unifypay.util.StringUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

/**
 * 商户注册
 * @author zsl
 * @version 2016年9月11日 上午11:32:16
 */
@WebServlet(urlPatterns="/MemberRegister")
public class MemberRegister extends HttpServlet {
	private static final long serialVersionUID = -5184785091677645426L;
	private static final Logger logger = Logger.getLogger(MemberRegister.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//不支持Get请求
		CommonUtil.responseObject(resp, Constant.ERROR_REQEST);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> param = CommonUtil.validate(request, response);
		if (param != null) {//验证通过 返回参数集合
			logger.info("接收到注册请求："+param);
			Map<String, Object> result = CommonUtil.createRespMap("10", "系统异常");
			Connection conn = null;//获取连接
			try {
				String partnerCode = request.getParameter("partnerCode");
				String memberName = param.get("memberName");
				String memberMobile = param.get("memberMobile");
				String memberCertno = param.get("memberCertno");
				String acctNo = param.get("acctNo");
				String bankNo = param.get("bankNo");
				String bankName = param.get("bankName");
				String orgNo = param.get("orgNo");
				String ip = param.get("ip");
				String gps = param.get("gps");
				String bizList = param.get("bizList");
				
				//业务参数验证
				if (StringUtil.isEmpty(memberName, memberMobile, memberCertno, acctNo, bankNo, bankName, ip, gps, bizList)) {
					logger.error(String.format("业务参数错误：memberName=%s, memberMobile=%s, memberCertno=%s, acctNo=%s, bankNo=%s, bankName=%s, ip=%s, gps=%s, bizList=%s",
							memberName, memberMobile, memberCertno, acctNo, bankNo, bankName, ip, gps, bizList));
					throw new RuntimeException("#200-业务参数错误");
				}
				//查询会员是否存在
				orgNo = orgNo == null || "".equals(orgNo) ? "00" : orgNo;
				orgNo = orgNo.length() == 1 ? "0" + orgNo : orgNo.length() > 2 ? orgNo.substring(0, 2) : orgNo;
				String memberNo = partnerCode + orgNo + memberMobile;
				if(DataDao.getInstance().getMember(memberNo) != null){
					logger.error(String.format("商户已存在：partnerCode=%s, memberMobile=%s", partnerCode, memberMobile));
					throw new RuntimeException("#201-商户已存在["+memberNo+"]");
				}
				Member member = new Member(memberNo, partnerCode, memberName, memberMobile, memberCertno, acctNo, bankNo, bankName, ip, gps);
				conn = DBUtil.getConnection();
				conn.setAutoCommit(false);
				if (!DataDao.getInstance().addMember(conn, member)) {
					logger.error(String.format("商户添加失败：memberName=%s, memberMobile=%s, partnerCode=%s", memberName, memberMobile, partnerCode));
					throw new RuntimeException("#10-商户添加失败");
				}
				
				JSONArray bizArray = JSONArray.parseArray(bizList);
				if (bizArray == null) {
					logger.error(String.format("业务列表格式有误：bizList=%s", bizList));
					throw new RuntimeException("#206-业务列表格式有误在");
				}
				for (Object object : bizArray) {
					JSONObject bizObj = (JSONObject) object;
					String bizcode = bizObj.getString("bizcode");
					String rate = bizObj.getString("rate");
					
					PartnerBiz partnerBiz = DataDao.getInstance().getPartnerBiz(partnerCode, bizcode);
					if (partnerBiz == null) {
						logger.error(String.format("合作商无此交易权限：partnerCode=%s, bizcode=%s", partnerCode, bizcode));
						throw new RuntimeException("#204-合作商无此交易权限");
					}
					if (Double.valueOf(rate) < Double.valueOf(partnerBiz.getBizrate())) {
						logger.error(String.format("商户最低扣率有误：partnerCode=%s, rate=%s", partnerCode, rate));
						throw new RuntimeException("#205-商户扣率有误");
					};
					
					DataDao.getInstance().addMemberBiz(conn, memberNo, bizcode, rate, "", "");
				}
				conn.commit();//提交事务
				result = CommonUtil.createRespMap("00", "商户注册成功");
				result.put("memberNo", memberNo);
			} catch(JSONException e){
				if (conn != null){
					try {
						conn.rollback();
					} catch (SQLException e1) {
						e1.printStackTrace();
					}//事務回滾
				}
				result = CommonUtil.createRespMap("10", "bizList格式有误");
			} catch (Exception e) {
				String message = e.getMessage();
				if (message.startsWith("#")) {
					result = CommonUtil.createRespMap(message.substring(1, message.indexOf("-")), message.substring(message.indexOf("-") + 1));
				} else {
					result = CommonUtil.createRespMap("10", e.getMessage());
					e.printStackTrace();
				}
				if (conn != null){
					try {
						conn.rollback();
					} catch (SQLException e1) {
						e1.printStackTrace();
					}//事務回滾
				}
			} finally {
				if (conn != null){
					try {
						conn.setAutoCommit(true);
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				logger.info("商户注册返回："+result);
				CommonUtil.responseObject(response, JSON.toJSONString(result));
			}
		}
	}
	
	public static void main(String[] args) {
		String i = "0";
		String bizratge = "0.35";
		System.out.println(Double.valueOf(i) < Double.valueOf(bizratge));
	}
}
